<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        .box {
            width: 200px;
            height: 200px;
            background: red;
            position: absolute;
            left: 0;
            top: 0;
        }
    </style>
</head>
<body>
    <div id="box1" class="box">box1</div>
    <div id="box2" class="box">box2</div>
    <script>
        function Drag (selector) {
            this.ele = document.querySelector(selector)
            if (selector) this.bindEvents()
        }

        Object.assign(Drag.prototype, {
            bindEvents () {
                this.ele.onmousedown = e => {
                    var disX = e.offsetX
                    var disY = e.offsetY
                    document.onmousemove = e => {
                        var left = e.clientX - disX
                        var top = e.clientY - disY
                        this.move(left, top)
                    }
                    document.onmouseup = function () {
                        document.onmousemove = null
                    }
                    return false
                }
            },
            move (left, top) {
                this.ele.style.left = left + 'px'
                this.ele.style.top = top + 'px'
            }
        })

        // 组合继承
        function LimitDrag (selector) {
            Drag.call(this, selector)
        }
        LimitDrag.prototype = new Drag()
        LimitDrag.prototype.constructor = LimitDrag
        // LimitDrag要重写一下Drag的move方法
        LimitDrag.prototype.move = function (left, top) {
            // 限定范围
            if (left < 0) left = 0
            if (top < 0) top = 0
            // TODO:右下角范围限定
            this.ele.style.left = left + 'px'
            this.ele.style.top = top + 'px'
        }

        new Drag('#box1')
        new LimitDrag('#box2')

    </script>
</body>
</html>